import tkinter as tk
from tkinter import scrolledtext, messagebox, ttk
import psutil
import subprocess

class SystemMonitorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("系统监控程序")  # 设置窗口标题

        self.language = 'Chinese'  # 默认语言设置为中文
        self.auto_refresh = False  # 自动刷新功能初始为关闭状态
        self.refresh_interval = 5000  # 刷新间隔时间（毫秒）
        self.remaining_time = self.refresh_interval // 1000  # 刷新倒计时时间

        # 当前语言标签
        self.language_label = tk.Label(root, text="当前语言: 中文")
        self.language_label.grid(row=0, column=0, columnspan=3, pady=10, padx=20, sticky="ew")

        # 自动刷新开关按钮
        self.refresh_toggle_button = tk.Button(root, text="开启自动刷新", command=self.toggle_refresh)
        self.refresh_toggle_button.grid(row=1, column=0, pady=10, padx=20, sticky="ew")

        # 刷新状态标签
        self.refresh_status_label = tk.Label(root, text="")
        self.refresh_status_label.grid(row=1, column=1, pady=10, padx=20, sticky="ew")

        # 手动刷新按钮
        self.manual_refresh_button = tk.Button(root, text="手动刷新", command=self.manual_refresh)
        self.manual_refresh_button.grid(row=1, column=2, pady=10, padx=20, sticky="ew")

        # 语言选择按钮框架
        self.language_buttons_frame = tk.Frame(root)
        self.language_buttons_frame.grid(row=2, column=0, columnspan=3, pady=20, padx=20, sticky="ew")

        # 语言选择按钮（中文）
        self.chinese_button = tk.Button(self.language_buttons_frame, text="中文", command=lambda: self.switch_language('Chinese'))
        self.chinese_button.grid(row=0, column=0, padx=10)

        # 语言选择按钮（日本语）
        self.japanese_button = tk.Button(self.language_buttons_frame, text="日本語", command=lambda: self.switch_language('Japanese'))
        self.japanese_button.grid(row=0, column=1, padx=10)

        # 语言选择按钮（英文）
        self.english_button = tk.Button(self.language_buttons_frame, text="English", command=lambda: self.switch_language('English'))
        self.english_button.grid(row=0, column=2, padx=10)

        # 硬件状态标签
        self.hardware_label = tk.Label(root, text="硬件状态:")
        self.hardware_label.grid(row=3, column=0, pady=10, padx=20, sticky="w")
        
        # 硬件状态显示区域
        self.hardware_display = scrolledtext.ScrolledText(root, width=80, height=10)
        self.hardware_display.grid(row=4, column=0, columnspan=3, padx=20, pady=10, sticky="nsew")

        # 软件状态标签
        self.software_label = tk.Label(root, text="软件状态:")
        self.software_label.grid(row=5, column=0, pady=10, padx=20, sticky="w")
        
        # 软件状态显示区域
        self.software_display = scrolledtext.ScrolledText(root, width=80, height=10)
        self.software_display.grid(row=6, column=0, columnspan=3, padx=20, pady=10, sticky="nsew")

        # 启动进程命令标签
        self.start_process_label = tk.Label(root, text="要启动的进程命令:")
        self.start_process_label.grid(row=7, column=0, pady=10, padx=20, sticky="w")

        # 启动进程命令输入框
        self.start_process_entry = tk.Entry(root, width=50)
        self.start_process_entry.grid(row=7, column=1, columnspan=2, padx=20, pady=10, sticky="ew")

        # 启动进程按钮
        self.start_process_btn = tk.Button(root, text="启动进程", command=self.start_process)
        self.start_process_btn.grid(row=8, column=0, columnspan=3, pady=10, padx=20, sticky="ew")

        # 终止进程PID标签
        self.terminate_process_label = tk.Label(root, text="要终止的进程PID:")
        self.terminate_process_label.grid(row=9, column=0, pady=10, padx=20, sticky="w")

        # 终止进程PID输入框
        self.terminate_process_entry = tk.Entry(root, width=50)
        self.terminate_process_entry.grid(row=9, column=1, columnspan=2, padx=20, pady=10, sticky="ew")

        # 终止进程按钮
        self.terminate_process_btn = tk.Button(root, text="终止进程", command=self.terminate_process)
        self.terminate_process_btn.grid(row=10, column=0, columnspan=3, pady=10, padx=20, sticky="ew")

        # 配置网格，使显示区域可以扩展
        root.grid_rowconfigure(4, weight=1)
        root.grid_rowconfigure(6, weight=1)
        root.grid_columnconfigure(1, weight=1)

        # 更新状态信息
        self.update_status()

    def switch_language(self, language):
        self.language = language
        if self.language == 'Chinese':
            self.language_label.config(text="当前语言: 中文")
            self.hardware_label.config(text="硬件状态:")
            self.software_label.config(text="软件状态:")
            self.start_process_label.config(text="要启动的进程命令:")
            self.start_process_btn.config(text="启动进程")
            self.terminate_process_label.config(text="要终止的进程PID:")
            self.terminate_process_btn.config(text="终止进程")
            self.refresh_toggle_button.config(text="开启自动刷新")
            self.manual_refresh_button.config(text="手动刷新")
        elif self.language == 'Japanese':
            self.language_label.config(text="現在の言語: 日本語")
            self.hardware_label.config(text="ハードウェアの状態:")
            self.software_label.config(text="ソフトウェアの状態:")
            self.start_process_label.config(text="プロセスを起動するコマンド:")
            self.start_process_btn.config(text="プロセスを起動")
            self.terminate_process_label.config(text="終了するプロセスのPID:")
            self.terminate_process_btn.config(text="プロセスを終了")
            self.refresh_toggle_button.config(text="自動更新を有効にする")
            self.manual_refresh_button.config(text="手動更新")
        else:
            self.language_label.config(text="Current Language: English")
            self.hardware_label.config(text="Hardware Status:")
            self.software_label.config(text="Software Status:")
            self.start_process_label.config(text="Command to Start Process:")
            self.start_process_btn.config(text="Start Process")
            self.terminate_process_label.config(text="PID to Terminate Process:")
            self.terminate_process_btn.config(text="Terminate Process")
            self.refresh_toggle_button.config(text="Enable Auto Refresh")
            self.manual_refresh_button.config(text="Manual Refresh")

        self.display_hardware_status()
        self.display_software_status()

    def get_hardware_status(self):
        # 获取硬件状态信息
        cpu_usage = psutil.cpu_percent(interval=1)
        memory_info = psutil.virtual_memory()
        disk_info = psutil.disk_usage('/')

        if self.language == 'Chinese':
            hardware_status = {
                'CPU使用率 (%)': cpu_usage,
                '总内存 (GB)': round(memory_info.total / (1024 ** 3), 2),
                '可用内存 (GB)': round(memory_info.available / (1024 ** 3), 2),
                '内存使用率 (%)': memory_info.percent,
                '总磁盘空间 (GB)': round(disk_info.total / (1024 ** 3), 2),
                '已用磁盘空间 (GB)': round(disk_info.used / (1024 ** 3), 2),
                '空闲磁盘空间 (GB)': round(disk_info.free / (1024 ** 3), 2),
                '磁盘使用率 (%)': disk_info.percent
            }
        elif self.language == 'Japanese':
            hardware_status = {
                'CPU使用率 (%)': cpu_usage,
                '総メモリ (GB)': round(memory_info.total / (1024 ** 3), 2),
                '利用可能メモリ (GB)': round(memory_info.available / (1024 ** 3), 2),
                'メモリ使用率 (%)': memory_info.percent,
                '総ディスクスペース (GB)': round(disk_info.total / (1024 ** 3), 2),
                '使用ディスクスペース (GB)': round(disk_info.used / (1024 ** 3), 2),
                '空きディスクスペース (GB)': round(disk_info.free / (1024 ** 3), 2),
                'ディスク使用率 (%)': disk_info.percent
            }
        else:
            hardware_status = {
                'CPU Usage (%)': cpu_usage,
                'Total Memory (GB)': round(memory_info.total / (1024 ** 3), 2),
                'Available Memory (GB)': round(memory_info.available / (1024 ** 3), 2),
                'Memory Usage (%)': memory_info.percent,
                'Total Disk Space (GB)': round(disk_info.total / (1024 ** 3), 2),
                'Used Disk Space (GB)': round(disk_info.used / (1024 ** 3), 2),
                'Free Disk Space (GB)': round(disk_info.free / (1024 ** 3), 2),
                'Disk Usage (%)': disk_info.percent
            }

        return hardware_status

    def display_hardware_status(self):
        hardware_status = self.get_hardware_status()
        self.hardware_display.delete(1.0, tk.END)  # 清空显示区域
        for key, value in hardware_status.items():
            self.hardware_display.insert(tk.END, f"{key}: {value}\n")  # 显示硬件状态

    def get_software_status(self):
        # 获取软件状态信息
        process_list = []
        for process in psutil.process_iter(attrs=['pid', 'name', 'status']):
            process_list.append(process.info)

        return process_list

    def display_software_status(self):
        software_status = self.get_software_status()
        self.software_display.delete(1.0, tk.END)  # 清空显示区域
        if self.language == 'Chinese':
            for process in software_status:
                self.software_display.insert(tk.END, f"PID: {process['pid']}, 名称: {process['name']}, 状态: {process['status']}\n")
        elif self.language == 'Japanese':
            for process in software_status:
                self.software_display.insert(tk.END, f"PID: {process['pid']}, 名前: {process['name']}, 状態: {process['status']}\n")
        else:
            for process in software_status:
                self.software_display.insert(tk.END, f"PID: {process['pid']}, Name: {process['name']}, Status: {process['status']}\n")

    def start_process(self):
        command = self.start_process_entry.get().split()  # 获取输入的命令
        try:
            subprocess.Popen(command)  # 启动进程
            if self.language == 'Chinese':
                messagebox.showinfo("成功", f"进程 '{' '.join(command)}' 启动成功。")
            elif self.language == 'Japanese':
                messagebox.showinfo("成功", f"プロセス '{' '.join(command)}' が正常に開始されました。")
            else:
                messagebox.showinfo("Success", f"Process '{' '.join(command)}' started successfully.")
        except Exception as e:
            if self.language == 'Chinese':
                messagebox.showerror("错误", f"启动进程 '{' '.join(command)}' 时出错: {str(e)}")
            elif self.language == 'Japanese':
                messagebox.showerror("エラー", f"プロセス '{' '.join(command)}' の開始中にエラーが発生しました: {str(e)}")
            else:
                messagebox.showerror("Error", f"Error starting process '{' '.join(command)}': {str(e)}")

    def terminate_process(self):
        pid = int(self.terminate_process_entry.get())  # 获取输入的PID
        try:
            process = psutil.Process(pid)
            process.terminate()  # 终止进程
            process.wait(timeout=3)
            if self.language == 'Chinese':
                messagebox.showinfo("成功", f"PID为 {pid} 的进程已成功终止。")
            elif self.language == 'Japanese':
                messagebox.showinfo("成功", f"PID {pid} のプロセスは正常に終了しました。")
            else:
                messagebox.showinfo("Success", f"Process with PID {pid} terminated successfully.")
        except psutil.NoSuchProcess:
            if self.language == 'Chinese':
                messagebox.showerror("错误", f"未找到PID为 {pid} 的进程。")
            elif self.language == 'Japanese':
                messagebox.showerror("エラー", f"PID {pid} のプロセスが見つかりません。")
            else:
                messagebox.showerror("Error", f"No process with PID {pid} found.")
        except psutil.TimeoutExpired:
            if self.language == 'Chinese':
                messagebox.showerror("错误", f"在超时时间内未能终止PID为 {pid} 的进程。")
            elif self.language == 'Japanese':
                messagebox.showerror("エラー", f"PID {pid} のプロセスをタイムアウト期間内に終了できませんでした。")
            else:
                messagebox.showerror("Error", f"Failed to terminate process with PID {pid} within the timeout period.")
        except Exception as e:
            if self.language == 'Chinese':
                messagebox.showerror("错误", f"终止PID为 {pid} 的进程时出错: {str(e)}")
            elif self.language == 'Japanese':
                messagebox.showerror("エラー", f"PID {pid} のプロセスを終了中にエラーが発生しました: {str(e)}")
            else:
                messagebox.showerror("Error", f"Error terminating process with PID {pid}: {str(e)}")

    def update_status(self):
        if self.auto_refresh:
            self.display_hardware_status()
            self.display_software_status()
            self.remaining_time = self.refresh_interval // 1000
            if self.language == 'Chinese':
                self.refresh_status_label.config(text=f"距离下次刷新还有 {self.remaining_time} 秒")
            elif self.language == 'Japanese':
                self.refresh_status_label.config(text=f"次の更新まで {self.remaining_time} 秒")
            else:
                self.refresh_status_label.config(text=f"{self.remaining_time} seconds until next refresh")
            self.countdown()

    def countdown(self):
        if self.auto_refresh and self.remaining_time > 0:
            self.remaining_time -= 1
            if self.language == 'Chinese':
                self.refresh_status_label.config(text=f"距离下次刷新还有 {self.remaining_time} 秒")
            elif self.language == 'Japanese':
                self.refresh_status_label.config(text=f"次の更新まで {self.remaining_time} 秒")
            else:
                self.refresh_status_label.config(text=f"{self.remaining_time} seconds until next refresh")
            self.root.after(1000, self.countdown)
        elif self.auto_refresh:
            if self.language == 'Chinese':
                self.refresh_status_label.config(text="刷新中")
            elif self.language == 'Japanese':
                self.refresh_status_label.config(text="更新中")
            else:
                self.refresh_status_label.config(text="Refreshing")
            self.update_status()

    def toggle_refresh(self):
        self.auto_refresh = not self.auto_refresh
        if self.auto_refresh:
            if self.language == 'Chinese':
                self.refresh_toggle_button.config(text="关闭自动刷新")
            elif self.language == 'Japanese':
                self.refresh_toggle_button.config(text="自動更新を無効にする")
            else:
                self.refresh_toggle_button.config(text="Disable Auto Refresh")
            self.remaining_time = self.refresh_interval // 1000
            self.update_status()
        else:
            if self.language == 'Chinese':
                self.refresh_toggle_button.config(text="开启自动刷新")
                self.refresh_status_label.config(text="")
            elif self.language == 'Japanese':
                self.refresh_toggle_button.config(text="自動更新を有効にする")
                self.refresh_status_label.config(text="")
            else:
                self.refresh_toggle_button.config(text="Enable Auto Refresh")
                self.refresh_status_label.config(text="")

    def manual_refresh(self):
        self.display_hardware_status()
        self.display_software_status()

if __name__ == "__main__":
    root = tk.Tk()
    app = SystemMonitorApp(root)
    root.mainloop()